<?php

namespace ChanTienGioi\Frontend;

use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Mvc\ModuleDefinitionInterface;

class Module implements ModuleDefinitionInterface
{

    /**
     * Registers the module auto-loader
     */
    public function registerAutoloaders()
    {
        $loader = new Loader();

        $loader->registerNamespaces(array(
            'ChanTienGioi\Frontend\Controllers' => __DIR__ . '/controllers/',
            'ChanTienGioi\Frontend\Models'      => __DIR__ . '/models/',
        ));

        $loader->register();
    }

    /**
     * Registers the module-only services
     *
     * @param Phalcon\DI $di
     */
    public function registerServices($di)
    {

        /**
         * Read configuration
         */
        $config = include __DIR__ . "/config/config.php";

        /**
         * Setting up the view component
         */
        $di['view'] = function () use ($config)
        {
            $view    = new View();
            $view->setViewsDir(__DIR__ . '/views/');
            $view->setLayoutsDir(__DIR__ . '/views/layouts/');
            $view->registerEngines(array(
                '.volt' => function ($view, $di) use ($config)
                {

                    $volt     = new View\Engine\Volt($view, $di);
                    $volt->setOptions(array(
                        'compiledPath'      => $config->application->cacheDir,
                        'compiledSeparator' => '_',
                    ));
                    $compiler = $volt->getCompiler();
                    $compiler->addFilter('md5', 'md5');
                    $compiler->addFilter('base64_encode', 'base64_encode');
                    $compiler->addFilter('current', 'current');

                    return $volt;
                },
                        '.phtml' => 'Phalcon\Mvc\View\Engine\Php'
                    ));
                    return $view;
                };

                /**
                 * Database connection is created based in the parameters defined in the configuration file
                 */
                $di['db'] = function () use ($config)
                {
                    return new DbAdapter(array(
                        "host"     => $config->database->host,
                        "username" => $config->database->username,
                        "password" => $config->database->password,
                        "dbname"   => $config->database->dbname
                    ));
                };
            }

        }
        